declare var tt: any;
import UrlEnum from "../Res/UrlEnum";
import Http, { IHttpMethod } from "../Net/Http";
import SdkInterface from "./SdkInterface";
import SdkTool from "./SdkTool";
import { ViewManager } from "../../Game/module/base/ViewManager";
import { SocketManager } from "../../Game/module/socket/SocketManager";
import { RandomUtils } from "../Utils/RandomUtils";
import EventMgr from "../Event/EventMgr";
import { view } from "cc";
import ProtoBufManager from "../../Game/proto/ProtoBufManager";
import { http } from "../../Game/proto/protoCmd";
import { GameModels } from "../../Game/module/socket/GameModels";
import Log from "../Log/Log";
export default class TtSdk implements SdkInterface {

    private videoAd: any;
    private callback: any;
    private target: any;
    private bannerAd: any;
    private interstitialAd: any;
    private customAd: any;
    /**
     * 初始化
     * @param callback 初始化成功后回调
     * @param target 监听对象
     */
    public init(callback: Function, target: Object): void {
        Log.ins.log(1, "TtSdk init");
        this.createRewardAd();
        this.checksidebar();
        tt.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        tt.onShareAppMessage(() => {
            return {
                title: '',
                imageUrl: ``
            }
        });
        tt.onShow(this.hotStart.bind(this));
    }

    /**
     * 登录
     * @param callback 登录成功后回调
     * @param target 监听对象
     */
    public login(): void {
        Log.ins.log(1, "TtSdk login");
        this.ttLoginCode();
    }

    private ttgetUserInfo(code, anonymousCode): void {
        const reqData = ProtoBufManager.ins.http.ReqEntry.create();
        reqData.Token = code;
        reqData.ChannelId = ProtoBufManager.ins.common.EChannelId.DY;
        const data: Uint8Array = ProtoBufManager.ins.http.ReqEntry.encode(reqData).finish();
        Http.ins.request(`${UrlEnum.httpUrl}entry`, data.slice().buffer, (data) => {
            if (!data) {
                EventMgr.emit(`serverError`);
                return;
            }
            ViewManager.ins.removeLoading();
            const rawData = new Uint8Array(data);
            const buf: http.RespEntry = ProtoBufManager.ins.http.RespEntry.decode(rawData);
            if (buf.ErrCode != ProtoBufManager.ins.common.ErrorCode.OK) {
                console.log(`%c登录游戏服失败,错误码:${buf.ErrCode}`, `color:blue;font-size:20px`);
                EventMgr.emit(`wxLogin`, false);
                return;
            }
            if (!buf.WSUrl.Host) {
                EventMgr.emit(`serverError`);
                return;
            }
            UrlEnum.socketip = `wss://${buf.WSUrl.Host}:${buf.WSUrl.Port}`;
            console.log(`%c登录游戏服成功,玩家uid:${buf.UId}`, `color:red;font-size:20px`);
            console.log(`%c游戏大厅路由:${buf.LobbyRoute}`, `color:red;font-size:20px`);
            console.log(`%c游戏服地址:${UrlEnum.socketip}`, `color:red;font-size:20px`);
            console.log(`%c${buf.IsNewAccount ? "是新用户" : "是老用户"}`, `color:red;font-size:20px`);
            SdkTool.ins.isFirst = buf.IsNewAccount;
            GameModels.info.playerInfo.UserId = buf.UId;
            GameModels.info.playerInfo.LobbyRoute = buf.LobbyRoute;
            // console.log(buf);

            // EventMgr.emit(`baseLogin`);
            // const info = JSON.parse(data);
            // console.log(`Web/s1001/login.php`, info);
            SocketManager.ins.connect();
        }, IHttpMethod.POST);
    }

    /**游戏服登录 */
    // private loginGameServer(): void {
    //     console.log(`游戏服登录`, `${UrlEnum.httpUrl}Web/s1001/login.php?openid=${SdkTool.ins.openid}`);
    //     Http.ins.request(`${UrlEnum.httpUrl}Web/s1001/login.php?openid=${SdkTool.ins.openid}`, ``, (data) => {
    //         const info = JSON.parse(data);
    //         console.log(`Web/s1001/login.php`, info);
    //         SocketManager.ins.connect();
    //         SdkTool.ins.isFirst = info == 1;
    //     }, IHttpMethod.GET);
    // }
    /**
     * 抖音登录
     * @param callback 
     */
    private ttLoginCode(): void {
        console.log('拉起抖音登录')
        tt.login({
            success: (res) => {
                console.log(res);
                if (res.code) {
                    console.log('登录成功：', res.code);
                    this.ttgetUserInfo(res.code, res.anonymousCode);
                } else {
                    console.log('登录失败！' + res.errMsg);
                }
            },
            fail: (res) => {
                console.log('登录方法调用失败', res);
            }
        }
        )
    }
    /**
     * 登出
     */
    public logout(): void {
        console.log("TtSdk logout");
    }

    /**
     * 退出
     */
    public exit(): void {
        console.log("TtSdk exit");
    }

    /**
     * 切换账号
     */
    public switchLogin(): void {
        console.log("TtSdk switchLogin");
    }

    /**
     * 数据上报
     * @param param 参数
     */
    public report(...param: any[]): void {
        console.log("TtSdk report");
    }

    /**
     * 数据上报
     * @param param 参数
     */
    public pay(...param: any[]): void {
        console.log("TtSdk pay");
    }

    /**
     * 播放广告
     */
    playRewardAd(callback: Function, target: any): void {
        this.callback = callback;
        this.target = target;
        ViewManager.ins.showloading();

        // 用户触发广告后，显示激励视频广告
        this.videoAd.show().catch(() => {
            // 失败重试
            this.videoAd.load()
                .then(() => this.videoAd.show())
                .catch(err => {
                    console.log('激励视频 广告显示失败');
                    // ViewManager.ins.showtips(`广告加载失败`);
                    this.onRewardAdCallback(false);
                });
        })
    }

    createRewardAd() {
        if (!this.videoAd) {
            this.videoAd = tt.createRewardedVideoAd({
                adUnitId: ``
            })

            this.videoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    // callback.call(target, true);
                    this.onRewardAdCallback(true);
                }
                else {
                    // 播放中途退出，不下发游戏奖励
                    // callback.call(target, false);
                    ViewManager.ins.showtips(`播放中途退出`);
                    this.onRewardAdCallback(false);
                }
            })

            this.videoAd.onError(err => {
                ViewManager.ins.removeLoading();
                tt.showToast({
                    title: "广告播放失败,请稍后再试~",
                    duration: 3000,
                    mask: true,

                });
                this.onRewardAdCallback(false);
            })
        }
    }

    onRewardAdCallback(success) {
        ViewManager.ins.removeLoading();
        if (this.callback) {
            if (success) {
                this.videoAd.load();
            }
            this.callback.call(this.target, success);
            this.callback = null;
        }
    }

    /**
     * 显示banner广告
     */
    showBannerAd(show: boolean): void {
        if (show) {
            // 在适合的场景显示 Banner 广告
            this.createBannerAd();
            this.bannerAd.show();
        }
        else {
            this.bannerAd.hide();
            this.bannerAd.destroy();
            this.bannerAd = null;
            this.createBannerAd();
        }
    }

    createBannerAd() {
        if (!this.bannerAd) {
            let sysInfo = tt.getSystemInfoSync();
            // 创建 Banner 广告实例，提前初始化
            var width = 320;
            this.bannerAd = tt.createBannerAd({
                adUnitId: 'adunit-',
                adIntervals: 30, // 自动刷新频率不能小于30秒
                style: {
                    left: sysInfo.screenWidth / 2 - width / 2,
                    top: sysInfo.screenHeight,
                    width: width
                }
            })

            this.bannerAd.onResize(res => {
                this.bannerAd.style.top = sysInfo.screenHeight - this.bannerAd.style.realHeight;
            })

            this.bannerAd.onError(err => {
                console.log(err)
            })
        }
    }

    createInterstitialAd() {
        // 创建插屏广告实例，提前初始化
        if (tt.createInterstitialAd && !this.interstitialAd) {
            this.interstitialAd = tt.createInterstitialAd({
                adUnitId: 'adunit-'
            })

            this.interstitialAd.onClose(res => {
                this.interstitialAd = null;
                this.createInterstitialAd();
            })
        }
    }

    showInterstitialAd() {
        // 在适合的场景显示插屏广告
        this.createInterstitialAd();
        if (this.interstitialAd) {
            this.interstitialAd.show().catch((err) => {
                console.error(err)
            })
        }
    }

    /**
     * 显示自定义广告
     */
    showCustomAd(show, top?, left?): void {
        // console.log(top, left);
        if (!this.customAd) {
            this.customAd = tt.createCustomAd({
                adIntervals: 30,
                adUnitId: "adunit-",
                style: {
                    fixed: true,
                    left: left,
                    top: top,
                },
            })
        }
        if (show) {
            this.customAd.show();
        }
        else {
            this.customAd.destroy();
            this.customAd = null;
        }
    }

    /**
     * 主动拉起转发
     * query key1=val1&key2=val2
     */
    shareAppMessage(title: string = "", query: any = null, shareCallback: any = null): void {
        title = title;
        // imageUrlId = imageUrlId;
        // imageUrl = imageUrl;
        var data = {
            title: title,
            // imageUrlId: imageUrlId,
            // imageUrl: imageUrl,
            query: query
        };
        tt.shareAppMessage({
            success() {
                console.log("分享成功");
            },
            fail(e) {
                console.log("分享失败", e);
            },
        });
    }
    /**
     * 获取应用启动参数
     *
     * @returns 返回应用启动参数，类型为 any
     */
    getAppParam(): any {
        const info = tt.getLaunchOptionsSync();
        SdkTool.ins.sceneAppId = info.scene;
        return info.query;
    }
    reconnect(): void {
        ViewManager.ins.showtips(`已掉线，正在重新连接...`);
        this.ttLoginCode();
    }
    /**是否支持侧片栏能力 */
    private checksidebar() {
        tt.checkScene({
            scene: "sidebar",
            success: (res) => {
                console.log("check scene success: ", res.isExist);
                //成功回调逻辑
                SdkTool.ins.sidebar = res.isExist;
            },
            fail: (res) => {
                console.log("check scene fail:", res);
                SdkTool.ins.sidebar = false;
                //失败回调逻辑
            }
        });
    }
    /**平台热启动 */
    private hotStart(res) {
        // console.log("启动参数：", res.query);
        // console.log("来源信息：", res.refererInfo);
        // console.log("场景值：", res.scene);
        // console.log("启动场景字段：", res.launch_from, ", ", res.location);
        if (res && res.scene && res.launch_from && res.location) {
            if (res.scene == `021036` && res.launch_from == `homepage` && res.location == `sidebar_card`) {
                SdkTool.ins.isSidebar = true;
            } else {
                SdkTool.ins.isSidebar = false;
            }
        } else {
            SdkTool.ins.isSidebar = false;
        }
    }
    /**
     * 跳转侧边栏
     */
    public navigateToScene(): void {
        tt.navigateToScene({
            scene: "sidebar",
            success: (res) => {
                console.log("navigate to scene success");
                // 跳转成功回调逻辑
            },
            fail: (res) => {
                console.log("navigate to scene fail: ", res);
                // 跳转失败回调逻辑
            },
        });
    }
    public getMenuButtonBoundingClientRect(): any {
        const res = tt.getMenuButtonBoundingClientRect();
        console.log(`获取菜单按钮（右上角胶囊按钮）:`, res);
        const pos = (res.height + res.top + res.height) * this.getWindowInfo();
        SdkTool.ins.topmenu = pos;
    }
    private getWindowInfo(): any {
        const res = tt.getSystemInfoSync();
        console.log(`获取窗口信息:`, res);
        const screenWidth: number = view.getVisibleSize().width;
        const screenHeight: number = view.getVisibleSize().height;
        return (res.screenHeight / screenHeight) + 1;
    }
    public setImRankData(val: number): any {
        tt.setImRankData({
            dateType: 0,
            value: val,
            priority: 0, //dataType为数字类型，不需要权重，直接传0
            extra: "extra",
            zoneId: 'default',
            success(res) {
                console.log(`setImRankData success res: `, res);
            },
            fail(res) {
                console.log(`setImRankData fail res: `, res.errMsg);
                tt.showToast({
                    title: "上传数据到排行榜失败~",
                    duration: 3000,
                    mask: true,
                });
            },
        });
    }
    public getImRankList(): void {
        tt.getImRankList({
            relationType: "all",
            dataType: 0,
            rankType: "all",
            suffix: "", //为空或不填，一般枚举类型不需要填后缀
            rankTitle: "最高分榜", //标题
            zoneId: 'default',
            success(res) {
                console.log(`getImRankData success res: `, res);
            },
            fail(res) {
                console.log(`getImRankData fail res: `, res.errMsg);
                tt.showToast({
                    title: "该应用不支持查看排行榜~",
                    duration: 3000,
                    mask: true,
                });
            },
        });
    }
    public vibrateShort(): void {
        tt.vibrateShort({
            success(res) {
                console.log(`${res}`);
            },
            fail(res) {
                console.log(`vibrateShort调用失败`);
            },
        });
    }
    /**
    * 将指定内容复制到剪贴板
    *
    * @param val 需要复制到剪贴板的内容
    */
    public setClipboardData(val: string): void {
        tt.setClipboardData({
            data: val,
            success(res) {
                tt.getClipboardData({
                    success(res) {
                        console.log(res.data + `:已复制到剪贴板`) // data
                        tt.showToast({
                            title: `已复制到剪贴板`
                        });
                    },
                    fail(res) {
                        ViewManager.ins.showtips(`当前平台不支持复制功能`);
                        console.log(`setClipboardData调用失败`);
                    },
                })
            }
        })
    }
}